package com.leyou.service.Impl;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.utils.BeanHelper;
import com.leyou.dto.OrderFormDTO;
import com.leyou.entity.Order;
import com.leyou.entity.OrderDetail;
import com.leyou.entity.OrderLogistics;
import com.leyou.item.client.ItemFeignClient;
import com.leyou.item.dto.AddressDTO;
import com.leyou.item.dto.SkuDTO;
import com.leyou.mapper.OrderMapper;
import com.leyou.service.OrderDetailService;
import com.leyou.service.OrderLogisticsService;
import com.leyou.service.OrderService;
import com.leyou.user.clients.UserClients;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ItemFeignClient itemClient;

    @Autowired
    private OrderDetailService orderDetailService;


    @Autowired
    private UserClients userClients;

    @Autowired
    private OrderLogisticsService orderLogisticsService;

    //下单
    @Override
    @Transactional
    public Long createOrder(OrderFormDTO orderFormDTO) {


        //获取订单中商品 skuId,与商品数量
        Map<Long, Integer> cartsMap = orderFormDTO.getCarts();


        //下单减库存
        itemClient.subtractStock(cartsMap);


        //获取商品的skuId集合
        Set<Long> skuIdSet = cartsMap.keySet();
        //List可以将set集合转换为List集合
        List<Long> skuIdList = new ArrayList<>(skuIdSet);
        //通过feign远程调用item服务根据skuId集合查询商品信息
        List<SkuDTO> skuDTOList = itemClient.querySkuListByIds(skuIdList);
        //总费用变量
        Long total_fee = 0L;
        //便利得到商品价格，
        for (SkuDTO skuDTO : skuDTOList) {
            total_fee += skuDTO.getPrice() * cartsMap.get(skuDTO.getId());
        }

        //创建订单
        Order order = new Order();
        //订单Id我们采用 自动填充
        //@TableId(type = IdType.ASSIGN_ID)

        //total_fee  总费用 = 商品*商品数量
        order.setTotalFee(total_fee);
        //actual_fee 实际费用 =总费用-优惠+运费
        order.setActualFee(total_fee);
        //post_fee   运费
        order.setPostFee(0L);
        //payment_type 付费类型
        order.setPaymentType(orderFormDTO.getPaymentType());
        //用户Id
        order.setUserId(UserContext.getUser().getId());
        //订单状态
        /*
         * 订单状态,1、未付款 2、已付款,未发货 3、已发货,未确认 4、确认收货，交易成功 5、交易取消，订单关闭 6、交易结束
         */
        order.setStatus(1);
        //保存订单到数据库
        this.save(order);




        //保存订单详情到数据量  一对多,一个用户对应一个订单，一个订单对应多个订单详情
        List<OrderDetail> OrderDetailList = skuDTOList.stream().map(skuDTO -> {
            OrderDetail orderDetail = new OrderDetail();
            //设置订单id
            orderDetail.setOrderId(order.getOrderId());
            //设置商品sukId
            orderDetail.setSkuId(skuDTO.getId());
            //设置商品数量
            orderDetail.setNum(cartsMap.get(skuDTO.getId()));
            //设置商品标题
            orderDetail.setTitle(skuDTO.getTitle());
            //设置特有规格
            orderDetail.setSpec(skuDTO.getSpecialSpec());
            //设置价格
            orderDetail.setPrice(skuDTO.getPrice());
            //设置图片。取处第一张
            orderDetail.setImage(StringUtils.substringBefore(skuDTO.getImages(), ","));
            return orderDetail;
        }).collect(Collectors.toList());
        //saveBatch批量保存
        orderDetailService.saveBatch(OrderDetailList);




        //保存订单物流信息 一个订单对应一个物流信息
        //请求用户服务，获取用户地址信息
        AddressDTO addressDTO = this.userClients.queryAddressById(UserContext.getUser().getId());
        //物流单号，物流名称在下单的时候，无法确定所以我们不考虑这些

        //直接将用户地址信息转换为订单物流信息
        OrderLogistics orderLogistics = BeanHelper.copyProperties(addressDTO, OrderLogistics.class);
        //设置主键
        orderLogistics.setOrderId(order.getOrderId());
        //保存订单物流信息
        orderLogisticsService.save(orderLogistics);



        return order.getOrderId();
    }
}
